<template>
  <div class="album-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      size="large"
    >
      <el-form-item label="相册名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入相册名称"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="相册描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请输入相册描述（可选）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="相册封面">
        <div class="cover-selector">
          <div class="cover-preview" @click="showCoverSelector = true">
            <img 
              v-if="coverPhoto" 
              :src="getThumbnailUrl(coverPhoto)" 
              alt="相册封面"
            />
            <div v-else class="cover-placeholder">
              <el-icon><Picture /></el-icon>
              <span>点击选择封面</span>
            </div>
          </div>
          <el-button 
            v-if="coverPhoto"
            type="danger" 
            plain 
            size="small"
            @click="removeCover"
          >
            移除封面
          </el-button>
        </div>
      </el-form-item>
      
      <el-form-item label="相册标签">
        <div class="tags-container">
          <el-tag
            v-for="tag in formData.tags"
            :key="tag"
            closable
            @close="removeTag(tag)"
            class="tag-item"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="inputRef"
            v-model="inputValue"
            class="tag-input"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">
            + 添加标签
          </el-button>
        </div>
      </el-form-item>
      
      <el-form-item>
        <div class="form-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    
    <!-- 封面选择对话框 -->
    <el-dialog
      v-model="showCoverSelector"
      title="选择封面"
      width="800px"
    >
      <PhotoSelector
        v-if="showCoverSelector"
        :photos="photos"
        :selected-ids="coverPhotoId ? [coverPhotoId] : []"
        @confirm="handleCoverSelected"
        @cancel="showCoverSelector = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElTag, ElIcon, ElDialog, ElMessage } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import type { Album, Photo } from '@/types';
import { albumService } from '@/services/albumService';
import { photoService } from '@/services/photoService';
import PhotoSelector from '@/components/common/PhotoSelector.vue';

// 组件属性
interface Props {
  albumId?: string; // 如果提供，则为编辑模式
}

const props = withDefaults(defineProps<Props>(), {
  albumId: undefined
});

// 组件事件
interface Emits {
  (e: 'submit', album: Album): void;
  (e: 'cancel'): void;
}

const emit = defineEmits<Emits>();

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
const inputRef = ref();

// 表单数据
const formData = ref({
  name: '',
  description: '',
  tags: [] as string[]
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入相册名称', trigger: 'blur' },
    { min: 1, max: 50, message: '相册名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述长度不能超过 500 个字符', trigger: 'blur' }
  ]
};

// 是否为编辑模式
const isEdit = computed(() => !!props.albumId);

// 提交状态
const submitting = ref(false);

// 封面相关
const coverPhotoId = ref<string | null>(null);
const coverPhoto = ref<Photo | null>(null);
const showCoverSelector = ref(false);
const photos = ref<Photo[]>([]);

// 标签输入相关
const inputVisible = ref(false);
const inputValue = ref('');

// 加载相册数据
const loadAlbum = async () => {
  if (!props.albumId) return;
  
  try {
    const album = await albumService.getAlbumById(props.albumId);
    if (!album) {
      ElMessage.error('相册不存在');
      return;
    }
    
    formData.value = {
      name: album.name,
      description: album.description || '',
      tags: album.tags || []
    };
    
    coverPhotoId.value = album.coverPhotoId || null;
    
    // 加载封面照片
    if (album.coverPhotoId) {
      coverPhoto.value = await photoService.getPhotoById(album.coverPhotoId);
    }
  } catch (error) {
    ElMessage.error('加载相册数据失败');
  }
};

// 加载所有照片
const loadPhotos = async () => {
  try {
    photos.value = await photoService.getPhotos();
  } catch (error) {
    ElMessage.error('加载照片列表失败');
  }
};

// 获取缩略图URL
const getThumbnailUrl = (photo: Photo) => {
  if (photo.thumbnailPath) {
    return `file://${photo.thumbnailPath}`;
  }
  return `file://${photo.filePath}`;
};

// 处理封面选择
const handleCoverSelected = (photoIds: string[]) => {
  if (photoIds.length > 0) {
    coverPhotoId.value = photoIds[0];
    const selectedPhoto = photos.value.find(p => p.id === photoIds[0]);
    if (selectedPhoto) {
      coverPhoto.value = selectedPhoto;
    }
  }
  showCoverSelector.value = false;
};

// 移除封面
const removeCover = () => {
  coverPhotoId.value = null;
  coverPhoto.value = null;
};

// 显示标签输入框
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    inputRef.value.focus();
  });
};

// 处理标签输入确认
const handleInputConfirm = () => {
  if (inputValue.value && !formData.value.tags.includes(inputValue.value)) {
    formData.value.tags.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = '';
};

// 移除标签
const removeTag = (tag: string) => {
  const index = formData.value.tags.indexOf(tag);
  if (index !== -1) {
    formData.value.tags.splice(index, 1);
  }
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitting.value = true;
    
    let album: Album;
    
    if (isEdit.value) {
      // 更新相册
      album = await albumService.updateAlbum(props.albumId!, {
        name: formData.value.name,
        description: formData.value.description,
        tags: formData.value.tags,
        coverPhotoId: coverPhotoId.value
      });
      ElMessage.success('相册更新成功');
    } else {
      // 创建相册
      album = await albumService.createAlbum({
        name: formData.value.name,
        description: formData.value.description,
        tags: formData.value.tags,
        coverPhotoId: coverPhotoId.value
      });
      ElMessage.success('相册创建成功');
    }
    
    emit('submit', album);
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新相册失败' : '创建相册失败');
  } finally {
    submitting.value = false;
  }
};

// 处理取消
const handleCancel = () => {
  emit('cancel');
};

// 组件挂载后加载数据
onMounted(() => {
  loadAlbum();
  loadPhotos();
});
</script>

<style scoped lang="scss">
.album-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  
  .cover-selector {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .cover-preview {
      width: 120px;
      height: 120px;
      border: 2px dashed var(--el-border-color);
      border-radius: 8px;
      overflow: hidden;
      cursor: pointer;
      transition: all 0.2s ease;
      
      &:hover {
        border-color: var(--el-color-primary);
      }
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .cover-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        color: var(--el-text-color-secondary);
        
        .el-icon {
          font-size: 24px;
          margin-bottom: 8px;
        }
        
        span {
          font-size: 12px;
        }
      }
    }
  }
  
  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .tag-item {
      margin-right: 8px;
      margin-bottom: 8px;
    }
    
    .tag-input {
      width: 100px;
      margin-right: 8px;
      margin-bottom: 8px;
    }
    
    .button-new-tag {
      margin-bottom: 8px;
    }
  }
  
  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 20px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .album-form {
    padding: 16px;
    
    .cover-selector {
      flex-direction: column;
      align-items: flex-start;
      
      .cover-preview {
        width: 100%;
        height: 200px;
      }
    }
    
    .form-actions {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>